<template>
	<view class="chart">
		<!-- 聊天背景 -->
		<image class='chart-bg' mode="scaleToFill" :src="chartBgUrl" @error="imageError"></image>
		<uni-nav-bar class='page-header' left-icon="left" @clickLeft='goBack'	:title="linkman.name"></uni-nav-bar>
		<view class="content">
			<view class="msg-wrap">
				<view v-for='item in chartlist' :key='item.id'>
					<view v-if='item.flag==="time"' class='time'>{{item.time}}</view>
					<view v-else :class="['msg-row',item.dir]">
						<image class='avatar' mode="scaleToFill" :src="item.avatarUrl || src" @error="imageError"></image>
						<text class='msg'>
							{{ item.msg}}
						</text>
					</view>
			
				</view>
			</view>
			<view class="send-wrap">
				<textarea v-model='currMsg' auto-height confirm-type='send' />
				<button class='send-btn' @click="sendMsg">发送</button>
			</view>
		</view>
	</view>
</template>

<script>
	// import io from 'socket.io-client';
	import dayjs from 'dayjs'
	export default {
		data() {
			return {
				/*
					聊天表字段设计
				    userID:'' 发消息的用户id
					text:'' // 消息文本内容c
					time:'' //消息发送的时间戳
					avatar:'' //用户头像
				 */
				// 当前联系人
				init: false,
				linkman: '',
				msglist: [],
				chartBgUrl: '',
				currMsg: '',
				src: 'https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/shuijiao.jpg',

			}
		},
		computed: {
			userID() {
				let res = uni.getStorageSync('userInfo');
				return res?.id;
			},
			chartlist() {
				// messagelist处理
				let result = this.msglist.map((item) => {
					// 联系人消息：渲染在左侧
					if (item.userID !== this.userID) {
						item.dir = 'left'
					} else { // 当前用户消息：渲染在右侧
						item.dir = 'right'
					}
					return item
				})
				// 初始化加载历史消息时展示时间
				if (this.init && result.length) {
					let timeStr = result[result.length - 1].time
					// time格式化处理
					let time = dayjs(time).format('M月D日 HH:mm:ss');
					console.log('格式化time------', time);
					result.push({
						flag: 'time',
						time
					})
				}
				console.log('chartlist-------', result)
				return result
			}
		},
		methods: {
			goBack(){
				uni.navigateTo({
					url:'/pages/linkMen/linkMen'
				})
			},
			// 获取消息列表
			getMsgList(init) {
				// 初始化获取历史消息
				this.init = init;
				uni.request({
					url: getApp().globalData.BaseUrl + '/msg/list',
					method: 'GET',
					data: {
						userID: this.userID,
						toUserID: this.linkman.id
						// page: 1,
						// size: 10
					},
					success: (res) => {
						let {
							statusCode,
							errMsg,
							data
						} = res
						if (statusCode !== 200) {
							uni.showToast({
								title: errMsg,
								duration: 2000
							});
							return false
						}
						this.msglist = data;
					},
					fail: (err) => {
						console.error(err);
					},
				});

			},
			// 发送
			sendMsg() {
				// 消息不能为空
				if (!this.currMsg) {
					uni.showToast({
						icon: 'error',
						title: '消息不能为空',
					});
					return false
				}

				let data = {
					flag: 'msg',
					userID: this.userID,
					toUserID: this.linkman.id,
					msg: this.currMsg
				}
				uni.sendSocketMessage({
					data: JSON.stringify(data)
				});
				this.msglist.push(data);
				// 清空输入框
				this.currMsg = ''

			},
			// 修改页面标题为当前联系人
			setPageTitle(title) {
				// 设置标题
				uni.setNavigationBarTitle({
					title
				});
			},
			// 获取自定义登录页背景图
			getUserConfig() {
				uni.request({
					url: getApp().globalData.BaseUrl + '/users/getUserConfig',
					method: 'GET',
					data: {
						userID: this.userID,
						type: 'chartBgUrl'
					},
					success: (res) => {
						console.log('getUserConfig-----res---', res)
						// 该结构为uiapp封装-不是后端返回的结构体
						let {
							statusCode,
							errMsg,
							data
						} = res
						if (statusCode !== 200) {
							uni.showToast({
								title: errMsg,
								duration: 2000
							});
							return false
						}
						this.chartBgUrl = data.chartBgUrl;
						console.log('chartBgUrl-----', this.chartBgUrl)
					},
					fail: (err) => {
						console.error(err);
					},
				});


			}
		},
		onLoad() {
			// 获取当前联系人信息
			let eventChannel = this.getOpenerEventChannel();
			eventChannel.on('linkman', (data) => {
				this.linkman = data
				// 当前联系人信息
				uni.setStorage({
					key: 'linkman',
					data: data,
					success: () => {
						// 设置页面标题
						this.setPageTitle(data.name);
						// 获取历史消息记录
						this.getMsgList('init');
					}
				})
			})
			// 监听ws-消息
			uni.$on('onWSMessage', (data) => {
				if (data.flag !== 'msg') {
					return false
				}
				this.msglist.push(data)
			});
			// 获取聊天背景图
			this.getUserConfig();
		}
	}
</script>

<style scoped lang="less">
	.chart {
		position: relative;
		::v-deep .page-header{
			.uni-navbar__content,.uni-navbar__header{
				background-color: transparent !important;
			}
			.uni-nav-bar-text{
				font-weight: bold;
			}
		}
		.chart-bg{
			position: absolute;
			z-index: 0;
			width:100%;
			height: 100vh;
			
		}
		.content{
			position: absolute;
			width: 100%;
			.msg-wrap {
				height: calc(100vh - 130px);
				overflow-y: auto;
			
				.time {
					margin: 50rpx auto;
					color: #8f939c;
					text-align: center;
				}
			
				.msg-row {
					display: flex;
					align-items: center;
			
					.msg {
						background-color: #95ec69;
						padding: 10px;
						border-radius: 8px;
					}
			
					&.left {
						justify-content: flex-start;
					}
			
					&.right {
						justify-content: flex-end;
			
						.avatar {
							order: 2;
							//margin-left: 10px;
						}
			
						.msg {
							order: 1
						}
					}
			
					.avatar {
						@size: 90rpx;
						width: @size;
						height: @size;
						border-radius: 10rpx;
						margin: 8px;
					}
				}
			}
			
			.send-wrap {
				width: 100%;
				position: fixed;
				bottom: 30px;
				display: flex;
				align-items: flex-end;
				padding: 10px;
				background: #e5e5e5c9;
			
				// box-shadow:inset 1px 1px 8px #065EAF;
				uni-textarea {
					width: 80%;
					//border:1px solid;
					background-color: #fff;
					border-radius: 6rpx;
			
					::v-deep .uni-textarea-wrapper {
						min-height: 30px !important;
					}
			
				}
			
				.send-btn {
					@h: 60rpx;
					width: 108rpx;
					height: @h;
					line-height: @h;
					background: #05c160;
					color: #fff;
					font-size: 20rpx;
					justify-self: end;
				}
			
			}
			
		}
	}
</style>